package com.moxigua.iotbox.func;

import com.moxigua.iotbox.base.Constants;
import com.moxigua.iotbox.func.event.BaseEvent;
import com.orhanobut.logger.Logger;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.greenrobot.eventbus.EventBus;

/**
 * Created by Junerver on 2017/6/3.
 * Feature: 回调函数，所有收到的MQTT消息都会在该回调中发送Event
 * Updated:
 */

public class MqttCallbackBus implements MqttCallback {
    @Override
    public void connectionLost(Throwable cause) {
        Logger.e(cause.getMessage());

        String offline = "[{ \"metric\":\t\"Online\",\"tags\":\t{\"clientID\":\t0},\"timestamp\":\t1262367484,\"value\":\t0}]";
        BaseEvent event = new BaseEvent();
        event.topic = Constants.TOPIC_SUB_REMOTE;
        event.message = new MqttMessage(offline.getBytes());
        EventBus.getDefault().post(event);
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) {
//        Logger.d(topic + "====" + message.toString());
        BaseEvent event = new BaseEvent();
        event.topic = topic;
        event.message = message;
        EventBus.getDefault().post(event);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
    }
}
